package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.properties.AliOssProperties;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/*通用接口*/
@RequestMapping("/admin/common")
@RestController
@Api(tags = "通用接口")
public class CommonController {

    private static final Logger log = LoggerFactory.getLogger(CommonController.class);
    /*注入配置代理*/
    @Autowired
    private AliOssProperties aliOssProperties;

    /*文件上传*/
    @PostMapping("/upload")
    @ApiOperation(value = "文件上传", httpMethod = "POST")
    public Result<String> upload(MultipartFile file) {
        log.info("文件上传:{}", file);
        String upload = null;
        try {
            /*防止文件名重复 利用UUID重命名文件*/
            String fileName = file.getOriginalFilename();//获取了原始的文件名称
            String extname = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));

            upload = AliOssUtil.upload(aliOssProperties.getEndpoint(), aliOssProperties.getBucketName(), file.getBytes(), extname);
        } catch (Exception e) {
            /*上传失败*/
            log.info("文件上传失败");
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }
        return Result.success(upload);
    }
}
